package com.example.expinterview.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.example.expinterview.dto.CollectDto;
import com.example.expinterview.entity.EiBuy;
import com.example.expinterview.entity.ResultBody;
import com.example.expinterview.entity.enums.ErrorCodeEnum;
import com.example.expinterview.mapper.EiArticleMapper;
import com.example.expinterview.mapper.EiBuyMapper;
import com.example.expinterview.service.IEiBuyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @classname: EiBuyServiceImpl
 * @description: TODO
 * @author: kaiser
 * @date: 2021/10/24 17:42
 * @version: 1.0
 */
@Service
public class EiBuyServiceImpl extends ServiceImpl<EiBuyMapper, EiBuy> implements IEiBuyService {

    private final EiArticleMapper mapper;

    @Autowired
    public EiBuyServiceImpl(EiArticleMapper mapper) {
        this.mapper = mapper;
    }

    private EiBuy getResult(Long userId, Long articleId) {
        HashMap<String, Long> map = new HashMap<>(2);
        map.put("user_id", userId);
        map.put("article_id", articleId);
        return baseMapper.selectOne(new QueryWrapper<EiBuy>().allEq(map));
    }

    @Override
    public ResultBody create(EiBuy collect) {
        EiBuy result = this.getResult(collect.getUserId(), collect.getArticleId());
        if (Objects.isNull(result)) {
            return ResultBody.status(SqlHelper.retBool(baseMapper.insert(collect)));
        } else {
            return ResultBody.fail(ErrorCodeEnum.INSERT_EXIST);
        }
    }

    @Override
    public ResultBody checkCollect(CollectDto collect) {
        HashMap<String, Boolean> booleanHashMap = new HashMap<>(1);
        EiBuy one = this.getResult(collect.getUserId(), collect.getArticleId());
        if (Objects.isNull(one)) {
            booleanHashMap.put("status", false);
        } else {
            booleanHashMap.put("status", true);
        }
        return ResultBody.success(booleanHashMap);
    }

    @Override
    public ResultBody listByUser(Long userId) {
        List<EiBuy> collectList = baseMapper.selectList(new QueryWrapper<EiBuy>().eq("user_id", userId));
        if (collectList.isEmpty()) {
            return ResultBody.fail(ErrorCodeEnum.RESULT_EMPTY);
        } else {
            List<Long> idList = collectList.stream().map(EiBuy::getArticleId).collect(Collectors.toList());
            return ResultBody.list(mapper.selectBatchIds(idList));
        }
    }
}
